package cn.tedu.custom.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class RpcServer {
    /**
     * 监听一个端口 等待客户端建立通信连接
     */
    public static void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(20000);
        //等待socket请求通信 有socket方法执行 没有 accept阻塞住线程
        while(true){
            System.out.println("waiting for connection...");
            Socket socket = server.accept();
            processSocket(socket);
            System.out.println("connection finished");
        }
    }

    private static void processSocket(Socket socket) throws IOException {
        //可以从socket中读到这个数据 做反序列化处理 拿到message字符串
        InputStream inputStream = socket.getInputStream();
        DataInputStream dis=new DataInputStream(inputStream);
        //反序列化
        String name = dis.readUTF();
        HelloServiceImpl helloService=new HelloServiceImpl();
        String result = helloService.sayHi(name);
        //通过socket给客户端返回回去
        DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
        dos.writeUTF(result);
    }
}
